package qrcode;

public class BitHelper {

  private int value;

  private int size;

  boolean[] bits;

  public BitHelper(final int value, int size) {
    if (size < 0 || size > 32)
      throw new IllegalArgumentException("Illegal size " + size + ".");
    this.value = value;
    this.size = size;
    bits = new boolean[size];
    int t = value;
    for (int i = 0; i < size; i++) {
      bits[i] = (t & 1) == 1;
      t >>= 1;
    }
  }

  public boolean isBitSet(int index) {
    return bits[index];
  }

  public int getSize() {
    return size;
  }

  public int getValue() {
    return value;
  }

  public static void main(String[] args) {
    BitHelper b = new BitHelper(32 + 4 + 1, 10);
    System.out.println(b.isBitSet(0));
    System.out.println(!b.isBitSet(1));
    System.out.println(b.isBitSet(2));
    System.out.println(!b.isBitSet(3));
    System.out.println(!b.isBitSet(4));
    System.out.println(b.isBitSet(5));
    System.out.println(!b.isBitSet(6));
    System.out.println(!b.isBitSet(7));
    System.out.println(!b.isBitSet(8));
    System.out.println(!b.isBitSet(9));
    System.out.println(getBitAtStartingAtMostSignificant(1, 1, 0));
    System.out.println(getBitAtStartingAtMostSignificant(1, 3, 2));
    System.out.println(getBitAtStartingAtMostSignificant(4, 9, 4));
    System.out.println(getBitAtStartingAtMostSignificant(4, 9, 5));
    System.out.println(getBitAtStartingAtMostSignificant(4, 9, 6));
  }

  public int getHammingDistance(BitHelper other) {
    if (other.getSize() != getSize()) {
      throw new IllegalArgumentException("Sizes of the bit sequences do not match (" + getSize() + " != "
          + other.getSize() + ").");
    }
    int distance = 0;
    for (int i = 0; i < size; i++) {
      if (bits[i] != other.bits[i]) {
        distance++;
      }
    }
    return distance;
  }

  public static boolean getBitAtStartingAtMostSignificant(int value, int numberOfUsedBits, int pos) {
    int shift = numberOfUsedBits - pos - 1;
    return ((value >> shift) & 1) == 1;
  }
}